package com.example.administrator.college02.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.administrator.college02.BaseFragment;
import com.example.administrator.college02.R;
import com.example.administrator.college02.adapter.CommonAdapter;
import com.example.administrator.college02.adapter.CustomArrayAdapter;
import com.example.administrator.college02.adapter.ViewHolder;
import com.example.administrator.college02.helper.AnalyzeJson;
import com.example.administrator.college02.model.CustomData;
import com.example.administrator.college02.model.ItemMessage;
import com.example.administrator.college02.pager.CycleViewPager;
import com.example.administrator.college02.utils.CommonNet;
import com.example.administrator.college02.utils.HorizontalListView;
import com.example.administrator.college02.widget.CustomDialog;
import com.example.administrator.college02.widget.HeartLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2016/7/12.
 */
public class FragmentSchoolChild extends BaseFragment {

    private ImageView bannerImageView = null;
    private List<ImageView> mImageViews = new ArrayList<>();
    private CommonAdapter<ItemMessage> mAdapter;
    private List<ItemMessage> mList;
    public CustomDialog customDialog = null;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case 0x123:
                    AnalyzeJson.setBanners(mContext,mImageViews,banners,bannerImageView,mCycleViewPager);
                    break;
                case 0x124:
                    customDialog.dismiss();
                    break;
            }
        }
    } ;
    @BindView(R.id.hlvCustomList) HorizontalListView mHlvCustomList;
    @BindView(R.id.gv_view_pager_school) GridView gvSchool;
    @BindView(R.id.heart_layout) HeartLayout mHeartLayout;
    private Random mRandom = new Random();
    private Timer mTimer = new Timer();
    private CustomData[] mCustomData = new CustomData[] {
            new CustomData(Color.parseColor("#48a4fd"), "校园概况",R.drawable.campus_1),
            new CustomData(Color.parseColor("#fa8a89"), "校园风采",R.drawable.campus_2),
            new CustomData(Color.parseColor("#2dd798"), "名人榜",R.drawable.campus_3),
            new CustomData(Color.parseColor("#ff8d5f"), "校园资讯",R.drawable.campus_4)
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view_pager_school,container,false);
        unbinder = ButterKnife.bind(this,view);
        mContext = getContext();
        banners = new ArrayList<>();
        mCycleViewPager = (CycleViewPager) getChildFragmentManager().findFragmentById(R.id.school_fragment_banner);
        AnalyzeJson.initBanner(mContext, mImageViews,banners,mCycleViewPager);
        AnalyzeJson.getDataFromSchoolServer(banners,handler,mCycleViewPager);
        setupCustomLists();
        getDataFromServer();
        customDialog = new CustomDialog(mContext,
                R.layout.dialog_layout, R.style.DialogTheme);
        customDialog.show();
        mAdapter = new CommonAdapter<ItemMessage>(mContext,R.layout.gv_item) {
            @Override
            public void conver(ViewHolder holder, ItemMessage itemMessage) {
                holder.setText(R.id.tv_gv_item,itemMessage.getTitle());
                holder.setPhotoFromNet(mContext,R.id.iv_gv_item,itemMessage.getUrlImage());
            }
        };
        gvSchool.setAdapter(mAdapter);
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                mHeartLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        mHeartLayout.addHeart(randomColor());
                    }
                });
            }
        }, 500, 200);
        return view;
    }
    private void getDataFromServer() {
        StringRequest request = new StringRequest(Request.Method.GET, CommonNet.SMALL_NEWS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        mList = new ArrayList<>();

                        try {
                            JSONArray jsonArray = new JSONObject(response).getJSONArray("data");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject object = jsonArray.getJSONObject(i);
                                Log.d("FragmentSchoolChild",object.toString());
                                String title = object.getString("school_news_title");
                                String urlImage = object.getString("school_news_thumb_ab");
                                ItemMessage message = new ItemMessage(title,urlImage);
                                mList.add(message);
                            }
                            mAdapter.bindData(mList);
                            Message message = new Message();
                            message.what = 0x124;
                            handler.sendMessage(message);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        Volley.newRequestQueue(mContext).add(request);
    }
    private void setupCustomLists() {
        // Make an array adapter using the built in android layout to render a list of strings
        CustomArrayAdapter adapter = new CustomArrayAdapter(getContext(), mCustomData);
        // Assign adapter to HorizontalListView
        mHlvCustomList.setAdapter(adapter);
        mHlvCustomList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        mBaseActivity.showFragment(FragmentSchoolDetails.class,"123",null,true);
                        break;
                    case 1:
                        mBaseActivity.showFragment(FragmentSchoolHistory.class,"123",null,true);
                        break;
                    case 2:
                        mBaseActivity.showFragment(FragmentStarPerson.class,"123",null,true);
                        break;
                    case 3:
                        mBaseActivity.showFragment(FragmentStarPerson.class,"123",null,true);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private int randomColor() {
        return Color.rgb(mRandom.nextInt(255), mRandom.nextInt(255), mRandom.nextInt(255));
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        mTimer.cancel();
    }
}
